package com.community.controller;

import com.community.pojo.User;
import com.community.service.AdminService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class LoginController {
    
    private final AdminService adminService;
    
    @Autowired
    public LoginController(AdminService adminService) {
        this.adminService = adminService;
    }
    
    @GetMapping("/loginForm")
    public String loginForm() {
        return "loginForm";
    }
    
    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpSession session,
                        RedirectAttributes redirectAttributes) {
        User user = adminService.findUserByUsername(username);
        if (user == null) {
            redirectAttributes.addFlashAttribute("message", "该用户不存在!");
            return "redirect:/loginForm";
        } else {
            if (password.equals(user.getPassword())) {
                session.setAttribute("user", user);
                if (user.getIsAdmin()) {
                    return "redirect:/adminMainPage";
                } else {
                    return "redirect:/userMainPage";
                }
            } else {
                redirectAttributes.addFlashAttribute("message", "密码错误!");
                return "redirect:/loginForm";
            }
        }
    }
    
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/loginForm";
    }
    
    @GetMapping("/adminMainPage")
    public String adminMainPage() {
        return "adminMainPage";
    }
    
    @GetMapping("/userMainPage")
    public String userMainPage() {
        return "userMainPage";
    }
}